package com.laker.autotest;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.EnableSpringUtil;
import com.laker.autotest.common.utils.TestNGUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableSpringUtil
@EnableScheduling
@Slf4j
public class AutoApiTestApplication {
    /**
     * 启动入口
     * <p>
     * 支持命令行参数：
     * java -jar easy-autotest.jar install - 安装浏览器
     * java -jar easy-autotest.jar test - 运行测试
     * java -jar easy-autotest.jar 其他 - 启动Spring Boot应用
     * </p>
     */
    public static void main(String[] args) {
        try {
            printStartupInfo(args);
            String command = parseCommand(args);
            switchCommand(command, args);
            printEndInfo();
        } catch (Exception e) {
            log.error("Application startup failed", e);
            System.exit(1);
        }
    }

    private static void printStartupInfo(String[] args) {
        log.info("Starting application with arguments: {}", String.join(" ", args));
    }

    /**
     * 解析命令参数，返回 install/test/other
     */
    private static String parseCommand(String[] args) {
        if (args.length == 0) {
            return "other";
        }
        if (argsContain(args, "install")) {
            return "install";
        }
        if (argsContain(args, "test")) {
            return "test";
        }
        return "other";
    }

    /**
     * 根据命令分支执行
     */
    private static void switchCommand(String command, String[] args) {
        switch (command) {
            case "test" -> runTests(args);
            default -> startSpringBootApp(args);
        }
    }

    private static void runTests(String[] args) {
        log.info("Running tests...");
        // 设置环境变量
        // 禁用定时任务
        System.setProperty("easy.cronjob.enabled", false + "");
        ConfigurableApplicationContext applicationContext = SpringApplication.run(AutoApiTestApplication.class, args);
        try {
            TestNGUtil.runWithTestNgXmlPath();
        } finally {
            log.info("Tests completed, shutting down application...");
            SpringApplication.exit(applicationContext);
        }
    }

    private static void startSpringBootApp(String[] args) {
        log.info("Starting Spring Boot application...");
        SpringApplication.run(AutoApiTestApplication.class, args);
    }

    private static void printEndInfo() {
        log.info("Gitee: https://gitee.com/lakernote/easy-auto-test");
    }

    private static boolean argsContain(String[] args, String keywords) {
        for (String arg : args) {
            if (StrUtil.contains(arg, keywords)) {
                return true;
            }
        }
        return false;
    }
}